﻿using FileManager.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FileManager.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index(string currPath = "")
        {
            List<FileModel> list = GetFiles(currPath);

            string[] arrTemp = currPath.TrimEnd('/').Split('/');
            arrTemp[arrTemp.Length - 1] = "";
            string parentPath = string.Join("/", arrTemp);

            ViewBag.ParentPath = parentPath;
            return View(list);
        }

        public ActionResult Upload()
        {
            HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
            return Json(new { });
        }

        /// <summary>
        /// 获取文件夹和文件列表
        /// </summary>
        /// <param name="path"></param>
        public List<FileModel> GetFiles(string currPath)
        {
            List<FileModel> list = new List<FileModel>();

            //拼接路径
            string FileRoot = GetRoot();
            string path = FileRoot + currPath.TrimStart('/').Replace('/', '\\');
            //文件夹
            string[] arrayFolders = Directory.GetDirectories(path);
            for (int i = 0; i < arrayFolders.Length; i++)
            {
                FileModel model = new FileModel();
                model.Name = Path.GetFileName(arrayFolders[i]);
                string tempPath = path.Substring(FileRoot.Length);
                tempPath = (tempPath.EndsWith("\\") ? tempPath : tempPath + "\\") + model.Name;
                model.Path = tempPath.Replace('\\', '/');
                model.Type = "dir";
                list.Add(model);
            }

            //文件
            string[] arrayFiles = Directory.GetFiles(path);
            for (int i = 0; i < arrayFiles.Length; i++)
            {
                FileModel model = new FileModel();
                model.Name = Path.GetFileName(arrayFiles[i]);
                //model.Path = (path.EndsWith("\\") ? path : path + "\\") + model.Name;
                model.Path = "http://localhost:5000/Files/MyFolder/" + currPath.TrimStart('/').TrimEnd('/') + "/" + model.Name;
                model.Type = Path.GetExtension(arrayFiles[i]);
                list.Add(model);
            }
            return list;
        }

        public string GetRoot()
        {
            string FileRoot = ConfigurationManager.AppSettings["FileRoot"];
            FileRoot = (FileRoot.EndsWith("\\") ? FileRoot : FileRoot + "\\") + "MyFolder\\";//根目录加上用户目录
            return FileRoot;
        }
    }
}